/*
 * @Author: Quinn
 * @Date: 2023-05-19 11:40:27
 * @LastEditors: quinn
 * @Description:
 */
import _ from "lodash";
import { get, post, postForm, postForm2, deleteFn, patch } from "./request.js";
import store from "../store";
import { API_HOST } from "@/assets/js/define";

const files = import.meta.globEager("./modules/**/*.js");

export function registerModule(apiMap = {}, urlPrefix = API_HOST) {
  const api = {};

  Object.keys(apiMap).map((name) => {
    const { url, method = "POST", formatUrl, ...rest } = apiMap[name] || {};
    api[name] = function (data = {}, options = {}) {
      options.headers = options.headers || {};
      options.headers.token =
        store.state.tokenv3 || window.$quinn.getStorage("tokenv3");
      let fullUrl = urlPrefix + url;
      if (typeof formatUrl === "function")
        fullUrl = formatUrl(fullUrl, data, options);
      options = _.merge({ method }, rest, options);

      options["Content-Type"] =
        options["contentType"] || "application/x-www-form-urlencoded";

      // 自定义url
      if (typeof rest.formatUrl === "function")
        fullUrl = rest.formatUrl(fullUrl, data, options);

      const m = `${method}`.toLocaleLowerCase();
      if (m === "post") {
        if ((options["Content-Type"] || "").includes("application/json")) {
          return post(fullUrl, data, options);
        }
        if ((options["Content-Type"] || "").includes("multipart/form-data")) {
          return postForm(fullUrl, data, options);
        }
        return postForm2(fullUrl, data, options);
      } else if (m === "patch") return patch(fullUrl, data, options);
      else if (m === "delete") return deleteFn(fullUrl, data, options);
      return get(fullUrl, data, options);
    };
  });

  return api;
}

const install = (app) => {
  for (const key in files) {
    if (key.includes("modules")) {
      const path = key.replace("./modules/", "").replace(".js", "");
      app.prototype[`$${path}`] = registerModule(files[key].default);
      window[`$${path}`] = registerModule(files[key].default);
    }
  }
};

export default {
  install,
};
